<?php

App::uses('AppController', 'Controller');

class NewsController extends AppController {

	var $uses = array('News');


	function detail($id = null) {
		$als = &$this->als;
		
		// Lấy thông tin chi tiết tin tức
		$news = $this->News->read(null, (int)$id);	
		$this->set('news', $news);
		
		// Get info danh muc cha va con
		App::uses('Category', 'Model');
		$Category = new Category();
		
		$category = $info = $Category->read(null, $news[$als]['category_id']);
		
		// Nếu là danh mục con thì lấy thông tin danh mục cha
		if($category['Category']['parent_id'] != 0) {
			$category = $Category->read(null, $info['Category']['parent_id']);
		}
		
		// Lấy danh sách tin tức khac
		$items = $this->News->getAll( array( 'id <>' => (int)$id, 'category_id' => $news[$als]['category_id']), 0, 8 );
		if(!empty($items)) {
			$view = new View( $this );
			$Text = $view->loadHelper( 'Text' );
			
	        foreach($items as $k => $v){
	        	$v['News']['desc'] =  strip_tags($v['News']['desc']);
	        	$v['News']['desc'] = $Text->truncate($v['News']['desc'], 200, array('ellipsis' => '...', 'exact' => false, 'html' => true));
				$items[$k] = $v;
	        }
		}
        $this->set('items', $items);
        
        $this->set('category', $category);
        $this->set('info', $info);
        $this->set('parent_cates', $Category->getAll($category['Category']['id'])); // Lấy danh mục con
	}
	
	/**
	 * Danh sach tin tuc
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function index($category_id = null) {
		
		// Get info danh muc cha
		App::uses('Category', 'Model');
		$Category = new Category();
		if(empty($category_id)) {
			$category = $info = $Category->find('first', array(
				'conditions' => array(
					'type' => 'news',
					'parent_id' => 0,
					'status' => 4
				)
			));
		} else {
			$info = $Category->read(null, (int)$category_id);
			$category = $Category->read(null, $info['Category']['parent_id']);
		}
		// Set url cho paging
		$params = $this->params;
		$url = array( 'controller' => 'news', 'action' => 'index', $category_id );
		$this->set('url', $url);
		
		$paginate = array( 'order'=> array('created' => 'desc'), 'limit' => 12);
		$this->paginate = $paginate;
        $items = $this->paginate(array('status' => 4, 'category_id' => $info['Category']['id']));
       
        if(!empty($items)) {
        	$view = new View( $this );
        	$Text = $view->loadHelper( 'Text' );
        	
	        foreach($items as $k => $v){
	        	$v['News']['desc'] =  strip_tags($v['News']['desc']);
	        	$v['News']['desc'] = $Text->truncate($v['News']['desc'], 200, array('ellipsis' => '...', 'exact' => false, 'html' => true));
				$items[$k] = $v;
	        }
        }
		
        
		$this->set('items', $items);
		$this->set('parent_cates', $Category->getAll($category['Category']['id'])); // Lấy danh mục con
		$this->set('category', $category);
		$this->set('info', $info);

		// Set Website title
        $this->set('title_for_layout' , $category['Category']['web_title']);
	}

	/**
	 * Danh sach san pham
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function admin_index($category_id = null) {
		$view = new View( $this );
        $Text = $view->loadHelper( 'Text' );
        
        App::uses('Codetbl', 'Model');
		$Codetbl = new Codetbl();
		
		App::uses('Category', 'Model');
		$Category = new Category();

		$paginate = $this->paginate;
        $als = &$this->als;
        
        // get condition from post data
        if (!empty($this->request->data)) {
            $this->_remove_empty_condition();

            // truong hop tim kiem
            if($this->request->data[$als]['action'] == 'search'){
                unset($this->request->data[$als]['action']);

                // reset post data
                $this->condPost = array();

                // create field like
                $like_fields = array($als . '.title', $als . '.als');

                // get condition after filter, get cond form $this->condPost
                $this->postConditions($this->request->data, '', $like_fields, $als);

                $this->Session->write($this->name . '_search', $this->condPost);
                $this->Session->write($this->name . '_data', $this->request->data);

            } elseif ($this->request->data[$als]['action'] == 'update' ){

            	if(!empty($this->request->data[$als]['status'])) {

        			$check = false;
					if(!empty($this->request->data['del'])) {
	                	foreach($this->request->data['del'] as $id => $v){
		                    if($v){
		                    	$check = true;
		                    	// Trường hợp xóa
        						if( $this->request->data[$als]['status'] == 9) {
		                        	$check = $this->_delete((int)$id);
        						} else {
        							$update = array('id' => (int)$id, 'status' => (int)$this->request->data[$als]['status']);
				                    $this->News->save($update, false);
        						}
		                    }
		                }
	                }

	                unset($this->request->data['del']);

	                if($check) {
						$this->Session->setFlash(__('Cập nhật trạng thái thành công'), 'success');
	                } else {
						$this->Session->setFlash(__('Bạn chưa chọn mẩu tin.'), 'error');
	                }
            	} else {
            		$this->Session->setFlash(__('Bạn chưa chọn hành động.'), 'error');
            	}
            }
        }

        // Get method
        if ($this->Session->check($this->name . '_search')) {
            $this->condPost = $this->Session->read($this->name . '_search');
            $this->request->data = $this->Session->read($this->name . '_data');
        } else {
			$this->condPost[$als . '.category_id'] = $category_id;
			$this->request->data = null;
        }
        
        // Get danh mục
        $categories = $Category->getListByType('news');
        
        if(empty($category_id)) {
        	$list_cate = array_keys($categories);
        	$this->condPost[$als . '.category_id'] = $category_id = $list_cate[0];
        } else {
        	$this->condPost[$als . '.category_id'] = (int)$category_id;
        }

		$paginate['order'] = array('sort' => 'asc');
		$paginate['limit'] = 25;
		$this->paginate = $paginate;

		if(empty($this->condPost[$als . '.status'])) {
			$this->condPost[$als . '.status'] = array(4,5);
		} else {
			$this->condPost[$als . '.status'] = (int)$this->condPost[$als . '.status'];
		}

        $items = $this->paginate($this->condPost);

        if(!empty($items))
        foreach($items as $k => $v){
        	$v[$als]['desc'] =  strip_tags($v[$als]['desc']);
        	$v[$als]['desc'] = $Text->truncate($v[$als]['desc'], 150, array('ellipsis' => '...', 'exact' => false, 'html' => true));
			$items[$k] = $v;
        }
        
        $this->set('categories', $categories);
        $this->set('category_id', $category_id);
		$this->set('items', $items);
		$this->set('status', $Codetbl->getList('COM', 'STS'));

		// thong tin hien thi cho trang
		$this->set('main_page_title', __('Tin Tức'));
        $this->set('main_page_description', __('Quản lý thông tin các tin tức'));

        $breadcrumb = array(
			array('name' => 'Tin tức', 'url' => 'news')
		);
		$this->set('breadcrumb', $breadcrumb);
	}

	/**
	 * Add
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function admin_add( $category_id, $id = null) {
		
		if(!empty($this->request->data))
		{
			$data = &$this->request->data[$this->als];

			$this->News->set($data);
			$errors = $this->News->invalidFields();

			//Save
			if(empty($errors)) {
				if(!empty($data['image']['name'])) {
					$data['image'] = $this->_upload($data['image']);
					if( isset($data['image_old'] )) {
						$path = PUBLIC_IMAGE_DETAIL.$data['image_old'] ;
						@unlink($path);
						$path = PUBLIC_IMAGE_THUMB.$data['image_old'] ;
						@unlink($path);
					}
				} else {
					if( isset($data['image_old'] )) {
						$data['image'] = $data['image_old'];
						unset($data['image_old']);
					} else {
						$data['image'] = '';
					}
				}


				// kiem tra edit
				if( empty($data['id']) ) {
					unset($data['id']);
					$data['status'] = 4;
				} else {
					$data['id'] = (int)$data['id'];
				}

				if($this->News->save($data, false)) {

					$this->Session->setFlash('Lưu tin tức thành công.', 'success');
					$this->redirect('/admin/news/' . $data['category_id'] );
				} else {
					$this->Session->setFlash('Lưu tin tức thất bại. Vui lòng xem lại thông tin bên dưới', 'error');
				}
			} else {
				if( isset($data['image_old'] ))
					$data['image'] = $data['image_old'];
				$this->Session->setFlash('Lưu tin tức thất bại.', 'error');
			}
		}

		// Truong hop show edit
		if( !empty( $id) && empty($this->request->data)) {
			$info = $this->News->read(array(),(int)$id);
			if(!empty($info)) {
				$this->request->data = $info;
			}
		}
		
		App::uses('Category', 'Model');
		$Category = new Category();
		
		$this->set('categories', $Category->getListByType('news'));
		$this->set('category_id', $category_id);

		// thong tin hien thi cho trang
		$this->set('main_page_title', __('Tin Tức'));
        $this->set('main_page_description', __('Quản lý thông tin các tin tức'));

        $breadcrumb = array(
			array('name' => 'Tin tức', 'url' => 'news'),
			array('name' => !empty( $id ) ? 'Sửa' : 'Thêm mới')
		);
		$this->set('breadcrumb', $breadcrumb);
	}

	/**
	 * Xem chi chi tiet
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function admin_info($id = null) {
		if(!empty($id)) {
			$news = $this->News->read(null, (int)$id );
			$this->set('info', $news);
		} else {
			$this->Session->setFlash('Không tìm thấy sản phẩm. Vui lòng thử lại sao', 'error');
			$this->redirect(array('action' => 'index'));
		}

		App::uses('Codetbl', 'Model');
		$Codetbl = new Codetbl();
		$this->set('status', $Codetbl->getList('COM', 'STS'));

		// thong tin hien thi cho trang
		$this->set('main_page_title', __('Tin Tức'));
        $this->set('main_page_description', __('Quản lý thông tin các tin tức'));

         $breadcrumb = array(
			array('name' => 'Tin tức', 'url' => 'news/index/' . $news[$this->als]['category_id']),
			array('name' => 'Xem chi tiết')
		);
		$this->set('breadcrumb', $breadcrumb);
	}

	/**
	 * delete san pham
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function _delete($id = null){
		if(!empty($id)) {
			$id = (int)$id;
			$info = $this->News->read(array(),$id);
			if( $this->News->delete($id)) {

				$path = PUBLIC_IMAGE_DETAIL.$info['News']['image'] ;
				@unlink($path);
				$path = PUBLIC_IMAGE_THUMB.$info['News']['image'] ;
				@unlink($path);

				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
		return false;
	}

		/**
	 * Change Sort
	 *
	 * @param type  meta
	 * @return type  meta
	 * @access public
	 */
	function admin_changeSort() {
		if(!empty($this->request->data['id']) && !empty($this->request->data['sort'])) {
			$this->Category->id = (int)$this->request->data['id'];

			if($this->Category->saveField('sort', (int)$this->request->data['sort']))
				$this->_responseJson(array('code' => 'success'));
			else
				$this->_responseJson(array('code' => 'danger'));
		}
		$this->_responseJson(array('code' => 'danger'));
	}


}
